package com.zyx.javademo.nio.channel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author Yaxi.Zhang
 * @since 2021/9/17 14:49
 */
public class ServerSocketChannelDemo {
    public static void main(String[] args) throws Exception {
        // 端口号
        int port = 8888;

        // buffer
        ByteBuffer buffer = ByteBuffer.wrap("hello zyx".getBytes());

        // ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 绑定
        ssc.socket().bind(new InetSocketAddress(port));

        // 设置非阻塞模式
        ssc.configureBlocking(false);

        // 监听有新链接传入
        while(true) {
            System.out.println("Waiting for connections");
            SocketChannel sc = ssc.accept();
            // 没有链接传入
            if(sc == null) {
                System.out.println("null");
                Thread.sleep(2000);
            } else {
                System.out.println("Incoming connection from: " + sc.socket().getRemoteSocketAddress());
                // 指针0
                buffer.rewind();
                sc.write(buffer);
                sc.close();
            }
        }

    }
}
